/* ========================================================================
 * zui-alertmsg.js  v1.3 beta2
 * ======================================================================== */
+function ($) {
    'use strict';

    // ALERTMSG GLOBAL ELEMENTS
    // ======================

    var $box, $alertbg, timer

    $(function() {
        var INIT_ALERTMSG = function() {
            $box     = $(FRAG.alertBoxFrag).hide().html('')
            $alertbg = $(FRAG.alertBackground).hide().html('')
            $('body').append('<!-- alert msg box -->').append($box).append('<!-- alert msg box mask bg -->').append($alertbg)
        }

        INIT_ALERTMSG()
    })

    // ALERTMSG CLASS DEFINITION
    // ======================
    var Alertmsg = function(options) {
        this.options   = options
        this.tools     = this.TOOLS()
        this.clearTime = null
    }

    Alertmsg.DEFAULTS = {
        displayPosition : 'topcenter', // Optional 'topleft, topcenter, topright, middleleft, middlecenter, middleright, bottomleft, bottomcenter, bottomright'
        displayMode     : 'slide',     // Optional 'none, fade, slide'
        autoClose       : null,
        alertTimeout    : 3000,
        mask            : null,
        types           : {error:'error', info:'info', warn:'warn', correct:'correct', confirm:'confirm'},
        fas             : {error:'icon-remove-sign', info:'icon-info-sign', warn:'icon-exclamation-sign', correct:'icon-check-sign', confirm:'icon-question-sign'},
        bottom          : 0,
        top             : 0
    }

    Alertmsg.prototype.TOOLS = function() {
        var that  = this
        var body_overflow = $('body').css('overflow')?$('body').css('overflow'):'auto';
        var tools = {
            showAlertBg:function(){
                //屏蔽页面滚动条
                $alertbg.height($(window).height()).css({top:$(window).scrollTop()});
                $('body').css({'overflow':'hidden'});
                $alertbg.show();
            },
            hideAlertBg:function(){
                $('body').css({'overflow':body_overflow});
                $alertbg.hide();
            },
            getTitle: function(key){
                return that.options.title || $.zui.regional.alertmsg.title[key]
            },
            keydownOk: function(event) {
                if (event.which == $.zui.keyCode.ENTER) {
                    event.data.target.trigger('click')
                    return false
                }
                return true
            },
            keydownEsc: function(event) {
                if (event.which == $.zui.keyCode.ESC) event.data.target.trigger('click')
            },
            openPosition: function() {
                var position = $.zui.alertMsg.displayPosition, mode = $.zui.alertMsg.displayMode, width = 460, height = $box.outerHeight(), startCss = {}, endCss = {}
                if(width>$(window).width()-50){
                    width = $(window).width()-50;
                }
                $box.css({width:width+'px'});

                if (position) {
                    if (that.options.displayPosition && that.options.displayPosition != 'topcenter')
                        position = that.options.displayPosition
                } else {
                    position = that.options.displayPosition
                }

                if (mode) {
                    if (that.options.displayMode && that.options.displayMode != 'silde')
                        mode = that.options.displayMode
                } else {
                    mode = that.options.displayMode
                }
                var _Top = $(window).scrollTop();

                switch (position) {
                case 'topleft':
                    startCss = {top:_Top - height, left:0, 'margin-left':0}
                    endCss   = {top:_Top}

                    break
                case 'topcenter':
                    startCss = {top:_Top - height, left:($(window).width()-width)/2, 'margin-left':0}
                    endCss   = {top:_Top}

                    break
                case 'topright':
                    startCss = {top:_Top - height, left:'auto', right:0, 'margin-left':0}
                    endCss   = {top:_Top}

                    break
                case 'middleleft':
                    startCss = {top:_Top + $(window).height()/2, left:0 - width, 'margin-left':0, 'margin-top':0 - height/2}
                    endCss   = {left:0}

                    break
                case 'middlecenter':
                    startCss = {top:_Top, 'margin-top':0 - height/2}
                    endCss   = {top:_Top + $(window).height()/2}

                    break
                case 'middleright':
                    startCss = {top:_Top + $(window).height()/2, left:'auto', right:0 - width, 'margin-top':0 - height/2}
                    endCss   = {right:0}

                    break
                case 'bottomleft':
                    startCss = {top:'auto', left:0, bottom:0 - height, 'margin-left':0}
                    endCss   = {bottom:that.options.bottom}

                    break
                case 'bottomcenter':
                    startCss = {top:'auto', bottom:0 - height}
                    endCss   = {bottom:that.options.bottom}

                    break
                case 'bottomright':
                    startCss = {top:'auto', left:'auto', right:0, bottom:0 - height, 'margin-left':0}
                    endCss   = {bottom:that.options.bottom}

                    break
                }
                if (mode == 'slide') {
                    $box.css(startCss).show().animate(endCss, 500)
                } else if (mode == 'fade') {
                    startCss.opacity = 0.1
                    $box.css(startCss).css(endCss).show().animate({opacity:1}, 500)
                } else {
                    $box.css(startCss).css(endCss).show()
                }
            },
            closePosition: function() {
                var position = $.zui.alertMsg.displayPosition, mode = $.zui.alertMsg.displayMode, width = 460, height = $box.outerHeight(), endCss = {}
                if(width>$(window).width()-50){
                    width = $(window).width()-50;
                }
                $box.css({width:width+'px'});
                if (position) {
                    if (that.options.displayPosition && that.options.displayPosition != 'topcenter')
                        position = that.options.displayPosition
                } else {
                    position = that.options.displayPosition
                }

                if (mode) {
                    if (that.options.displayMode && that.options.displayMode != 'silde')
                        mode = that.options.displayMode
                } else {
                    mode = that.options.displayMode
                }

                var _Top = $(window).scrollTop();
                switch (position) {
                case 'topleft':
                    endCss   = {top:_Top - height}

                    break
                case 'topcenter':
                    endCss   = {top:_Top - height}

                    break
                case 'topright':
                    endCss   = {top:_Top - height}

                    break
                case 'middleleft':
                    endCss   = {left:0 - width}

                    break
                case 'middlecenter':
                    endCss   = {top:_Top - height}

                    break
                case 'middleright':
                    endCss   = {right:0 - width}

                    break
                case 'bottomleft':
                    endCss   = {bottom:0 - height}

                    break
                case 'bottomcenter':
                    endCss   = {bottom:0 - height}

                    break
                case 'bottomright':
                    endCss   = {bottom:0 - height}

                    break
                }

                if (mode == 'slide') {
                    $box.animate(endCss, 500, function() {
                        that.tools.hideAlertBg();
                        $(this).hide().empty()
                    })
                } else if (mode == 'fade') {
                    $box.animate({opacity:0}, 500, function() {
                        that.tools.hideAlertBg();
                        $(this).hide().empty()
                    })
                } else {
                    $box.hide().remove()
                    that.tools.hideAlertBg();
                }
            },
            open: function(type, msg, buttons) {
                var tools = this, btnsHtml = '', $newbox, $btns, alertTimeout = $.zui.alertMsg.alertTimeout

                if (buttons) {
                    for (var i = 0; i < buttons.length; i++) {
                        var sRel = buttons[i].call ? 'callback' : ''
                        var sCls = buttons[i].cls  ? buttons[i].cls : 'default'
                        var sIco = (buttons[i].cls && buttons[i].cls == 'green') ? 'check' : 'close'

                        btnsHtml += FRAG.alertBtnFrag.replace('#btnMsg#', '<i class="icon icon-'+ sIco +'"></i> '+ buttons[i].name).replace('#callback#', sRel).replace('#class#', sCls)
                    }
                }
                $newbox =
                    $(FRAG.alertBoxFrag.replace('#type#', type)
                    .replace('#icon#', that.options.fas[type])
                    .replace('#title#', this.getTitle(type))
                    .replace('#message#', msg)
                    .replace('#btnFragment#', btnsHtml))
                    .hide()
                    .appendTo('body')

                if ($box && $box.length) $box.remove()
                $box = $newbox

                tools.openPosition()

                if (timer) {
                    clearTimeout(timer)
                    timer = null
                }

                if (that.options.mask == null) {
                    if (!(that.options.types.info == type || that.options.types.correct == type)) {
                        this.showAlertBg();
                    }
                }
                if (that.options.autoClose == null) {
                    if (that.options.types.info == type || that.options.types.correct == type) {
                        if (alertTimeout) {
                            if (that.options.alertTimeout && that.options.alertTimeout != 3000)
                                alertTimeout = that.options.alertTimeout
                        } else {
                            alertTimeout = that.options.alertTimeout
                        }
                        timer = setTimeout(function() { tools.close(that.options) }, alertTimeout)
                    }
                }

                $btns = $box.find('.btn')

                $btns.each(function(i) {
                    $(this).on('click', $.proxy(function() {
                            that.tools.close(that.options)

                            var call = buttons[i].call

                            if (typeof call === 'string')   call = call.toFunc()
                            if (typeof call === 'function') call.call()
                        }, that)
                    )

                    if (buttons[i].keyCode === $.zui.keyCode.ENTER) {
                        $(document).on('keydown.zui.alertmsg.ok', {target:$btns.eq(i)}, tools.keydownOk)
                    }
                    if (buttons[i].keyCode === $.zui.keyCode.ESC) {
                        $(document).on('keydown.zui.alertmsg.esc', {target:$btns.eq(i)}, tools.keydownEsc)
                    }
                })
            },
            alert: function(type, msg, btnoptions) {
                $.extend(that.options, typeof btnoptions === 'object' && btnoptions)

                var op      = $.extend({}, {okName:$.zui.regional.alertmsg.btnMsg.ok, okCall:null}, that.options)
                var cls = (type=='error'?'warning':'default');
                var buttons = [
                    {name:op.okName, call:op.okCall, cls:cls, keyCode:$.zui.keyCode.ENTER}
                ]

                this.open(type, msg, buttons)
            },
            close: function(op) {
                $(document).off('keydown.zui.alertmsg.ok').off('keydown.zui.alertmsg.esc')
                if($.isExitsFunction(op.closeCall)){
                    op.closeCall();
                }
                this.closePosition()
            }
        }

        return tools
    }

    Alertmsg.prototype.error = function(msg, btnoptions) {
        this.tools.alert(this.options.types.error, '<i class="icon-remove-sign txt-red"></i>'+msg, btnoptions)
    }

    Alertmsg.prototype.info = function(msg, btnoptions) {
        this.tools.alert(this.options.types.info, '<i class="icon-info-sign txt-default"></i>'+msg, btnoptions)
    }

    Alertmsg.prototype.warn = function(msg, btnoptions) {
        this.tools.alert(this.options.types.warn, '<i class="icon-info-sign icon-rotate-180 txt-red"></i>'+msg, btnoptions)
    }

    Alertmsg.prototype.ok = function(msg, btnoptions) {
        this.tools.alert(this.options.types.correct, '<i class="icon-checked-sign txt-success"></i>'+msg, btnoptions)
    }

    Alertmsg.prototype.correct = function(msg, btnoptions) {
        this.tools.alert(this.options.types.correct, msg, btnoptions)
    }

    Alertmsg.prototype.confirm = function(msg, btnoptions) {
        $.extend(this.options, typeof btnoptions === 'object' && btnoptions)

        var op      = $.extend({}, {okName:$.zui.regional.alertmsg.btnMsg.ok, okCall:null, cancelName:$.zui.regional.alertmsg.btnMsg.cancel, cancelCall:null}, this.options)
        var buttons = [
            {name:op.okName, call:op.okCall, cls:'green', keyCode:$.zui.keyCode.ENTER},
            {name:op.cancelName, call:op.cancelCall, cls:'warning', keyCode:$.zui.keyCode.ESC}
        ]

        this.tools.open(this.options.types.confirm, '<i class="icon-question-sign txt-red"></i>'+msg, buttons)
    }

    // ALERTMSG PLUGIN DEFINITION
    // =======================

    function Plugin(option) {
        var args     = arguments,
            property = option,
            alertmsg = 'zui.alertmsg',
            $body    = $('body'),
            data     = $body.data(alertmsg)

        return this.each(function () {
            var $this   = $(this),
                options = $.extend({}, Alertmsg.DEFAULTS, typeof option === 'object' && option)

            if (!data) {
                data = new Alertmsg(options)
            } else {
                data.options = options
            }
            if(typeof property === 'string'){
                if(property === 'info' || property === 'ok' || property === 'correct'){
                    data.options.displayPosition = "topright";
                    data.options.bottom = -24;
                }
                else if (property === 'error')
                {
                    data.options.displayPosition = "middlecenter";
                }
            }
            $body.data(alertmsg, data)

            if (typeof property === 'string' && $.isFunction(data[property])) {
                [].shift.apply(args)
                if (!args) data[property]()
                else data[property].apply(data, args)
            }
        })
    }

    var old = $.fn.alertmsg

    $.fn.alertmsg             = Plugin
    $.fn.alertmsg.Constructor = Alertmsg

    // ALERTMSG NO CONFLICT
    // =================

    $.fn.alertmsg.noConflict = function () {
        $.fn.alertmsg = old
        return this
    }

    // NOT SELECTOR
    // ==============

    $.zui.alertmsg = function() {
        Plugin.apply($('body'), arguments)
    }
    // NAVTAB DATA-API
    // ==============

    $(document).on('click.zui.alertmsg.data-api', '[data-toggle="alertmsg"]', function(e) {
        var $this = $(this), data = $this.data(), options = data.options, type

        if (options) {
            if (typeof options === 'string') options = options.toObj()
            if (typeof options === 'object') {
                $.extend(data, options)
            }
        }

        type = data.type
        if (!type) return false
        if (!data.msg) {
            if (options.msg) data.msg = options.msg
        }

        Plugin.call($this, type, data.msg || type, data)

        e.preventDefault()
    })

}(jQuery);
function alert(msg, title) {
    var data = {};
    if(title) {
        data = {title: title};
    }
    $.zui.alertmsg('error', msg, data);
}